package org.jaaksi.test.cardview;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import java.util.List;

/**
 * Created by Fcy on 2015/11/21.
 */
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.SimpleViewHolder>
{
	private Context mContext;
	private List<String> mInfo;

	public MyAdapter(Context mContext, List<String> mInfo)
	{
		this.mContext = mContext;
		this.mInfo = mInfo;
	}

	/**
	 * 相当于在getView中创建ViewHolder
	 * 
	 * @param parent
	 * @param viewType
	 *            item的类型 相当于之前的 getViewType
	 * @return
	 */
	@Override
	public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
	{
		View view = LayoutInflater.from(mContext).inflate(R.layout.item_card, parent,
		        false);
		return new SimpleViewHolder(view);
	}

	/**
	 * 绑定ViewHolder后的操作 相当于之前的getView中创建ViewHolder后的操作
	 * 
	 * @param holder
	 * @param position
	 */
	@Override
	public void onBindViewHolder(SimpleViewHolder holder, final int position)
	{
		if (mInfo == null || mInfo.isEmpty())
			return;
		holder.title.setText(mInfo.get(position));
		holder.root.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (onItemClick != null)
				{
					onItemClick.onItemClick(v, position);
				}
			}
		});
	}

	@Override
	public int getItemCount()
	{
		return mInfo == null ? 0 : mInfo.size();
	}

	// ====================

	public static class SimpleViewHolder extends RecyclerView.ViewHolder
	{

		public TextView title;
		public View root;

		public SimpleViewHolder(View itemView)
		{
			super(itemView);
			// 相当于之前的ViewHolder
			title = (TextView) itemView.findViewById(R.id.title);
			root = itemView.findViewById(R.id.root);
		}
	}

	public void setOnItemClick(OnItemClick onItemClick)
	{
		this.onItemClick = onItemClick;
	}

	public OnItemClick onItemClick;

	public interface OnItemClick
	{
		void onItemClick(View view, int position);
	}
}
